﻿using System;
using System.ComponentModel;
using System.Linq;
using EDMDesigner.Business.MSL.Condition;
using EDMDesigner.Business.Util;

namespace EDMDesigner.Business.MSL.Association
{
    public class AssociationMapping : INotifyPropertyChanged
    {
        private CSDL.Association.Association _association;

        public AssociationMapping(CSDL.Association.Association association)
        {
            _association = association;
        }

        internal bool MappingInit { get; private set; }
        internal void BeginInit()
        {
            MappingInit = true;
        }
        internal void EndInit()
        {
            MappingInit = false;
        }

        public bool IsCompletlyMapped
        {
            get
            {
                return SSDLTableMapped != null && _association.PropertiesEnd.All(np => np.EntityType.Keys.All(k => np.Mapping.Any(pm => pm.Property == k && pm.Column != null && pm.Column.EntityType == SSDLTableMapped)));
            }
        }

        private SSDL.EntityType.EntityType _ssdlTableMapped;
        public SSDL.EntityType.EntityType SSDLTableMapped 
        {
            get { return _ssdlTableMapped; }
            set 
            {
                if (_ssdlTableMapped == value)
                    return;
                _ssdlTableMapped = value;
                OnTableChanged();
            }
        }

        private EventedObservableCollection<ColumnConditionMapping> _conditionsMapping;
        public EventedObservableCollection<ColumnConditionMapping> ConditionsMapping
        {
            get
            {
                if (_conditionsMapping == null)
                    _conditionsMapping = new EventedObservableCollection<ColumnConditionMapping>();
                return _conditionsMapping;
            }
        }

        protected virtual void OnTableChanged()
        {
            if (MappingInit)
                return;
            if (TableChanged != null)
            {
                ConditionsMapping.Clear();
                TableChanged();
            }
            OnPropertyChanged("SSDLTableMapped");
            OnPropertyChanged("IsCompletlyMapped");
        }
        public event Action TableChanged;

        protected internal virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}
